﻿<div class="easyui-layout" data-options="fit:true">
    <!-- Begin of toolbar -->
    <div id="wu-toolbar-pm">
        <div class="wu-toolbar-button">
            <a href="#" class="easyui-linkbutton" iconCls="icon-add" onclick="openAddPm()" plain="true">添加</a>
            <a href="#" class="easyui-linkbutton" iconCls="icon-edit" onclick="openEditPm()" plain="true">修改</a>
            <a href="#" class="easyui-linkbutton" iconCls="icon-remove" onclick="removePm()" plain="true">删除</a>
            <a href="#" class="easyui-linkbutton" iconCls="icon-remove" onclick="reloadPm()" plain="true">刷新</a>
        </div>
    </div>
    <!-- End of toolbar -->
    <table id="wu-datagrid-pm" class="easyui-datagrid" toolbar="#wu-toolbar-pm"></table>
</div>
<!-- Begin of easyui-dialog -->
<div id="wu-dialog-pm" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'" style="width:400px; padding:10px;">
    <form id="wu-form-pm" method="post">
        <table>
            <tr>
                <td width="60" align="right">图片标题:</td>
                <td>
                    <input type="text" class="wu-text" required="required" name="title">
                </td>
            </tr>
            <tr>
                <td width="60" align="right">跳转路径:</td>
                <td>
                    <input type="text" class="wu-text" required="required" name="jumpPath">
                </td>
            </tr>
            <tr>
                <td align="right">图片用途:</td>
                <td>
                    <!-- <input type="text" name="picClassify" required="required" class="wu-text" /> -->
                    <select id="pm-select-yongtu" class="easyui-combobox" style="width:200px;" name="picClassify" required="required"></select>
                </td>
            </tr>
            <tr>
                <td align="right">图片文件:</td>
                <td>
                    <input class="easyui-filebox" type="file" required="required" style="width:300px" onchange="change_photo()" id="file_upload"
                        name="file_upload2" />
                </td>
            </tr>
            <input type="text" name="id" style="display:none;">
            <input type="text" name="picUrl" style="display:none;" id="img-path">
        </table>
        <div id="Imgdiv" style="text-align:center;">
            <img id="Img" width="260px" />
        </div>
    </form>
</div>
<!-- End of easyui-dialog -->
<script type="text/javascript">
    // 时间默认过滤器
    $.fn.datebox.defaults.formatter = function (date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        return y + '-' + d + '-' + m;
    }
    /**
     * Name 添加记录
     */
    function addPm() {
        $('#wu-form-pm').form('submit', {
            url: $.webConfig.apiUrl + 'picture/addPicture',
            success: function (data) {
                var data = JSON.parse(data);
                if (data['return_code']) {
                    $.messager.alert('信息提示', '提交成功！', 'info');
                    $('#wu-dialog-pm').dialog('close');
                    $('#wu-datagrid-pm').datagrid('reload');
                } else {
                    $.messager.alert('信息提示', '提交失败！', 'info');
                }
            }
        });
    }

    /**
     * Name 修改记录
     */
    function editPm() {
        $('#wu-form-pm').form('submit', {
            url: $.webConfig.apiUrl + 'picture/updatePicture',
            success: function (data) {
                var data = JSON.parse(data);
                if (data['return_code'] == 1) {
                    $.messager.alert('信息提示', '提交成功！', 'info');
                    $('#wu-dialog-pm').dialog('close');
                    $('#wu-datagrid-pm').datagrid('reload');
                } else {
                    $.messager.alert('信息提示', '提交失败！', 'info');
                }
            }
        });
    }

    /**
     * Name 删除记录
     */
    function removePm() {
        var items = $('#wu-datagrid-pm').datagrid('getSelections');
        console.log(items)
        if (items.length == 0) {
            $.messager.alert('信息提示', '你没选中哦...', 'info');
            return;
        }
        $.messager.confirm('信息提示', '确定要删除该记录？', function (result) {
            if (result) {
                var items = $('#wu-datagrid-pm').datagrid('getSelections');
                var ids = [];
                $(items).each(function () {
                    ids.push(this.id);
                });
                console.log(JSON.stringify(ids))
                if (!items) {
                    $.messager.alert('信息提示', '你没选中哦...', 'info');
                    return;
                }

                //alert(ids);return;
                $.ajax({
                    type: 'post',
                    url: $.webConfig.apiUrl + 'picture/delPicture',
                    data: {
                        id: JSON.stringify(ids)
                    },
                    success: function (data) {
                        var data = JSON.parse(data);
                        if (data['return_code'] == 1) {
                            $.messager.alert('信息提示', '删除成功！', 'info');
                            $('#wu-datagrid-pm').datagrid('reload');
                        } else {
                            $.messager.alert('信息提示', '删除失败！', 'info');
                        }
                    }
                });
            }
        });
    }

    /**
     * Name 打开添加窗口
     */
    function openAddPm() {
        $('#wu-form-pm').form('clear');
        $('#Imgdiv #Img').removeAttr('src');
        $('#wu-dialog-pm').dialog({
            closed: false,
            modal: true,
            title: "添加信息",
            cache: false,
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: addPm
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#wu-dialog-pm').dialog('close');
                }
            }]
        });
        $('#pm-select-yongtu').combobox('setValue', '2');
    }

    /**
     * Name 打开修改窗口
     */
    function openEditPm() {
        $('#wu-form-pm').form('clear');
        var item = $('#wu-datagrid-pm').datagrid('getSelected');

        if (!item) {
            $.messager.alert('信息提示', '你没选中哦...', 'info');
            return;
        }

        item.addtime = dataFormate(item.addtime);

        $('#wu-form-pm').form('load', item);

        console.log(item)
        $('#Imgdiv #Img').attr('src', item['picUrl']);
        $("#img-path").val(item['picUrl']);


        $('#wu-dialog-pm').dialog({
            closed: false,
            modal: true,
            title: "修改信息",
            cache: false,
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: editPm
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#wu-dialog-pm').dialog('close');
                }
            }]
        });

        $('#pm-select-yongtu').combobox('setValue', item['picClassify']);
    }

    /**
     * Name 分页过滤器
     */
    function pagerFilter(data) {
        var pageData = {
            total: 18,
            rows: []
        };

        if (data['return_code'] == 1) {
            if (data['total']) {
                pageData['total'] = data['total'];
            }
            pageData['rows'] = data['return_body'];
        }

        return pageData;
    }


    var photo_fun_obj = {
        // 1: {
        //     id: 1,
        //     title: '图片新闻'
        // },
        2: {
            id: 2,
            title: '工作动态'
        },
        // 3: {
        //     id: 3,
        //     title: '友情链接'
        // },
        4: {
            id: 4,
            title: '浮窗'
        }
    }
    var user_obj = JSON.parse($.cookie('gn_userObj'));
    var photo_fun_arr = [];
    if (user_obj['isSuperAdministrator'] == 1) {
        photo_fun_arr = [
            // {
            //     id: 1,
            //     title: '图片新闻'
            // }, 
            {
                id: 2,
                title: '工作动态'
            },
            // {
            //     id: 3,
            //     title: '友情链接'
            // }, 
            {
                id: 4,
                title: '浮窗'
            }
        ];

    } else {
        var picarr = user_obj['pic'].split(",");
        console.log(picarr)
        for (var i = 0; i < picarr.length; i++) {
            if (photo_fun_obj[picarr[i]]) {

                photo_fun_arr.push(photo_fun_obj[picarr[i]])

            }
        }

    }





    $('#pm-select-yongtu').combobox({
        valueField: 'id',
        textField: 'title',
        data: photo_fun_arr,
        editable: false,
        onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
            var val = $(this).combobox("getData");
            for (var item in val[0]) {
                if (item == "id") {
                    $(this).combobox("setValue", val[0][item]);
                }
            }
        }
    });

    /**
     * Name 载入数据
     */
    $('#wu-datagrid-pm').datagrid({
        queryParams: {
            id: JSON.parse($.cookie('gn_userObj'))['id'],
            type: JSON.parse($.cookie('gn_userObj'))['isSuperAdministrator'],
            title: ''
        },
        url: $.webConfig.apiUrl + 'picture/getListPicture',
        loadFilter: pagerFilter,
        singleSelect: false,
        pageSize: 20,
        pagination: false,
        multiSort: true,
        fitColumns: true,
        fit: true,
        columns: [
            [{
                    checkbox: true
                },
                {
                    field: 'id',
                    title: 'id',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'title',
                    title: '图片标题',
                    width: 180,
                    sortable: true
                },
                {
                    field: 'jumpPath',
                    title: '跳转路径',
                    width: 180,
                    sortable: true
                },
                {
                    field: 'picClassify',
                    title: '图片用途',
                    width: 180,
                    sortable: true,
                    formatter: function (value, row, index) {
                        if (photo_fun_obj[value]) {
                            return photo_fun_obj[value]['title'];
                        } else {
                            return value;
                        }

                    }
                },
                {
                    field: 'picUrl',
                    title: '图片',
                    width: 180,
                    sortable: true,
                    formatter: function (value, row, index) {
                        return '<img width="90px" src="' + value + '"/>';
                    }
                }
            ]
        ]
    });
    // 时间格式化
    function dataFormate(value) {
        var date = new Date(value);
        var year = date.getFullYear().toString();
        var month = (date.getMonth() + 1);
        var day = date.getDate().toString();
        var hour = date.getHours().toString();
        var minutes = date.getMinutes().toString();
        var seconds = date.getSeconds().toString();
        if (month < 10) {
            month = "0" + month;
        }
        if (day < 10) {
            day = "0" + day;
        }
        if (hour < 10) {
            hour = "0" + hour;
        }
        if (minutes < 10) {
            minutes = "0" + minutes;
        }
        if (seconds < 10) {
            seconds = "0" + seconds;
        }
        return year + "-" + month + "-" + day;
        //  + " " + hour + ":" + minutes + ":" + seconds;
    }

    // 刷新页面
    function reloadPm() {
        $('#wu-datagrid-pm').datagrid('reload');
    }


    // ajax 异步上传
    function ajaxFileUpload() {
        $.ajaxFileUpload({
            url: '/upload.php', //用于文件上传的服务器端请求地址
            secureuri: false, //是否需要安全协议，一般设置为false
            fileElementId: 'file_upload', //文件上传域的ID
            dataType: 'json', //返回值类型 一般设置为json
            success: function (data, status) //服务器成功响应处理函数
            {
                if (data['status'] == true) {
                    $('#Imgdiv #Img').attr('src', data['path'][0]);
                    $("#img-path").val(data['path'][0]);
                    // 清空
                    var file = $('#file_upload');
                    file.after(file.clone().val(""));
                    file.remove();
                } else {
                    $.messager.alert('信息提示', data['error'][0], 'info');
                }
            },
            error: function (data, status, e) //服务器响应失败处理函数
            {
                console.log(data)
            }
        })
        return false;
    }




    // 图片上传
    function change_photo() {
        ajaxFileUpload();
        // PreviewImage($("input[name='file_upload2']")[0], 'Img', 'Imgdiv');
    }
    // 图片上传预览
    function PreviewImage(fileObj, imgPreviewId, divPreviewId) {
        var allowExtention = ".jpg,.bmp,.gif,.png"; //允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value;  
        var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
        var browserVersion = window.navigator.userAgent.toUpperCase();
        if (allowExtention.indexOf(extention) > -1) {
            if (fileObj.files) { //HTML5实现预览，兼容chrome、火狐7+等  
                if (window.FileReader) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
                    }
                    reader.readAsDataURL(fileObj.files[0]);
                } else if (browserVersion.indexOf("SAFARI") > -1) {
                    alert("不支持Safari6.0以下浏览器的图片预览!");
                }
            } else if (browserVersion.indexOf("MSIE") > -1) {
                if (browserVersion.indexOf("MSIE 6") > -1) { //ie6  
                    document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
                } else { //ie[7-9]  
                    fileObj.select();
                    if (browserVersion.indexOf("MSIE 9") > -1)
                        fileObj.blur(); //不加上document.selection.createRange().text在ie9会拒绝访问  
                    var newPreview = document.getElementById(divPreviewId + "New");
                    if (newPreview == null) {
                        newPreview = document.createElement("div");
                        newPreview.setAttribute("id", divPreviewId + "New");
                        newPreview.style.width = document.getElementById(imgPreviewId).width + "px";
                        newPreview.style.height = document.getElementById(imgPreviewId).height + "px";
                        newPreview.style.border = "solid 1px #d2e2e2";
                    }
                    newPreview.style.filter =
                        "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection
                        .createRange().text + "')";
                    var tempDivPreview = document.getElementById(divPreviewId);
                    tempDivPreview.parentNode.insertBefore(newPreview, tempDivPreview);
                    tempDivPreview.style.display = "none";
                }
            } else if (browserVersion.indexOf("FIREFOX") > -1) { //firefox  
                var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
                if (firefoxVersion < 7) { //firefox7以下版本  
                    document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
                } else { //firefox7.0+                      
                    document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[
                        0]));
                }
            } else {
                document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
            }
        } else {
            alert("仅支持" + allowExtention + "为后缀名的文件!");
            fileObj.value = ""; //清空选中文件  
            if (browserVersion.indexOf("MSIE") > -1) {
                fileObj.select();
                document.selection.clear();
            }
            fileObj.outerHTML = fileObj.outerHTML;
        }
    }
</script>